package com.zing.WebSocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {
    // 存放会话对象
    private static Map<String, Session> sessionMap =  new HashMap<String, Session>();

    // 监听连接成功
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid){ //  @PathParam("sid") 路径变量
        System.out.println("连接成功:" + sid);
        sessionMap.put(sid, session);
    }

    // 监听收到客户端消息
    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid){
        System.out.println("收到消息" +sid +": " + message);
    }

    // 监听连接关闭
    @OnClose
    public void onClose(@PathParam("sid") String sid){
        System.out.println(sid + " :连接关闭");
        sessionMap.remove(sid);
    }

    // 群发
    public void sendToAllClient(String message) {
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
